<template>
    <a-card :bordered="false">
        <!-- <div class="table-operator">
            <a-button v-if="hasPerm('rdrecord32.Add')" type="primary" icon="plus" @click="handleAdd()">新建</a-button>
            <a-button v-if="hasPerm('rdrecord32.Delete')" type="primary" icon="minus" @click="handleDelete(selectedRowKeys)"
                :disabled="!hasSelected()" :loading="loading">删除</a-button>
            <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
        </div> -->
        <a-modal :visible="visibleUpload" @cancel="() => { this.visibleUpload = false; }">
            <a-upload name="file" :multiple="false" :showUploadList="false" :action="$rootUrl + leading" :headers="headers"
                @change="handleChange" style="display: inline-block" accept=".xlsx,.xls" class="upload-list-inline"
                >
                <a-button type="primary">
                    <a-icon type="upload" />
                    上传Excel数据
                </a-button>
            </a-upload>
            <template slot="footer">
                <a-button @click="() => { this.visibleUpload = false; }">关闭</a-button>
            </template>
        </a-modal>
        <div class="table-page-search-wrapper" style="margin-bottom: 20px;">
            <a-form layout="inline">
                <a-row :gutter="10">


                    <a-col style="display: flex;justify-content: space-between;">
                        <div>
                            <a-button type="primary" icon="download" @click="downloadTemplate">下载模板</a-button>
                            <a-button type="primary" style="margin:0 8px;" icon="upload"
                                @click="handleImport()">导入</a-button>
                            <a-button type="primary" icon="plus" :disabled="disabled" @click="association">
                                新增
                            </a-button>
                        </div>
                        <div>
                            <a-form-item label="客户">
                                <div style="display: flex;">
                                    <a-input disabled style="width: 300px;" v-model="customName" placeholder="客户名称">
                                    </a-input>
                                    <a-button type="primary" :disabled="disabled" @click="handleOpenChoose">
                                        <a-icon type="search" />
                                    </a-button>
                                </div>
                            </a-form-item>
                        </div>
                    </a-col>
                    <!-- <a-col :md="4" :sm="24">
                        <a-form-item>
                            <a-input v-model="queryParam.Keyword" placeholder="关键字" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                        <a-button type="primary" @click="() => {
                            this.pagination.current = 1
                            this.getDataList()
                        }">查询</a-button>
                        <a-button style="margin-left: 8px" @click="repossess">重置</a-button>
                    </a-col> -->
                </a-row>
            </a-form>
        </div>

        <a-table ref="table" :scroll="{ y: 530 }" :columns="columns" :rowKey="(row, index) => row.Id" :dataSource="data"
            :pagination="pagination" :loading="loading" @change="handleTableChange" :bordered="true" size="small">
            <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
            <span slot="action" slot-scope="text, record">
                <template>
                    <a @click="handleEdit(record.Id)">编辑</a>
                    <a-divider type="vertical" />
                    <a @click="handleDelete(record.Id)">删除</a>
                </template>
            </span>
        </a-table>
        <!-- 关联业务员 -->
        <a-drawer :title="title" placement="right" :closable="false" :visible="visible" width="80%" @close="close">

            <div>
                <a-row>
                    <a-form-model :model="form" ref="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-col :span="8">
                            <a-form-model-item label="业务编号" prop="cCusCode">
                                <a-input v-model="form.cCusCode" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="业务名称" prop="cCusName">
                                <a-input v-model="form.cCusName" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="省/直辖市" prop="cProvince">
                                <a-select v-model="form.cProvince" :disabled="title == '审核'" allowClear
                                    default-value="省/直辖市" style="width: 100%" @change="city($event)">
                                    <a-select-option v-for="(item, dei) in list" :key="item.Id" :disabled="title == '审核'"
                                        :value="item.Id">
                                        {{ item.Name }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="市" prop="cCity">
                                <a-select v-model="form.cCity" :disabled="title == '审核'" allowClear default-value="市"
                                    style="width: 100%" @change="village($event)">
                                    <a-select-option v-for="(item, dei) in listChildren" :key="item.Id" :value="item.Id">
                                        {{ item.Name }}
                                    </a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="区县" prop="cCounty">
                                <a-select v-model="form.cCounty" :disabled="title == '审核'" allowClear default-value="选择县级"
                                    style="width: 100%">
                                    <a-select-option v-for="(item, dei) in county" :key="item.Id" :value="item.Id"> {{
                                        item.Name
                                    }}</a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="开户银行" prop="cCusBank">
                                <a-input v-model="form.cCusBank" :disabled="title == '审核'" autocomplete="off"
                                    placeholder="开户银行" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="银行账号" prop="cCusAccount">
                                <a-input v-model="form.cCusAccount" :disabled="title == '审核'" autocomplete="off" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="税号" prop="cCusTaxnumber">
                                <a-input v-model="form.cCusTaxnumber" :disabled="title == '审核'" autocomplete="off" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="电话" prop="cCusHand">
                                <a-input v-model="form.cCusHand" :disabled="title == '审核'" autocomplete="off"
                                    placeholder="电话" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="邮箱地址" prop="cCusEmail">
                                <a-input v-model="form.cCusEmail" :disabled="title == '审核'" autocomplete="off"
                                    placeholder="邮箱地址" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-model-item label="地址" prop="District">
                                <a-textarea v-model="form.District" :auto-size="{ minRows: 5 }" :disabled="title == '审核'"
                                    autocomplete="off" />
                            </a-form-model-item>
                        </a-col>
                    </a-form-model>
                </a-row>
            </div>
            <div :style="{
                position: 'absolute',
                right: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
                zIndex: 1,
            }">
                <a-button :style="{ marginRight: '8px' }" @click="handleCancel">取消</a-button>
                <a-button type="primary" @click="handleOk">保存</a-button>
            </div>
        </a-drawer>
        <!-- 关联商家 -->
        <a-modal title="选择客户" :visible="businessVisible" @ok="handleCustomOK" width="70%" @cancel="() => {
            this.businessVisible = false;
            this.CustomSeach = '';
        }">
            <div style="display: flex;margin-bottom: 20px;">
                <a-input v-model="CustomSeach" style="width: 200px;margin-right: 20px;" placeholder="请输入客户名称"
                    @keydown.enter="getCustomData" />
                <a-button type="primary" @click="() => {
                    this.Custompagination.current = 1
                    this.getCustomData()
                }">查询</a-button>
            </div>
            <a-table ref="table" :scroll="{ y: 530 }" :columns="columnsCus" :rowKey="(row, index) => row"
                :dataSource="CustomData" :pagination="Custompagination" :loading="Customloading"
                @change="handleTableCustomChange" :row-selection="rowSelectionBusiness" :bordered="true" size="small">
                <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
            </a-table>
        </a-modal>
    </a-card>
</template>

<script>
import moment from 'moment'
const columns = [
    { title: '业务编号', dataIndex: 'BusinessCode', width: '30%' },
    { title: '业务名称', dataIndex: 'BusinessName' },
    { title: '财务编号', dataIndex: 'FinancialCode' },
    { title: '财务名称', dataIndex: 'FinancialName' },
    { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '100px' }
]
const columnsSalesman = [
    { title: '业务员编号', dataIndex: 'cCusCode' },
    { title: '业务员名称', dataIndex: 'cCusName' },
    { title: '地址', dataIndex: 'District' },
    { title: '联系方式', dataIndex: 'cCusPhone' },
]
const columnsCus = [
    { title: '客户编号', dataIndex: 'cCusCode' },
    { title: '客户名称', dataIndex: 'cCusName' },
]
export default {
    components: {
    },
    mounted() {
        this.loading = true;
        this.getlist()
        this.$http.post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition',
            {
                "PageIndex": this.Custompagination.current, "PageRows": this.Custompagination.pageSize,
                "SortField": "Id", "SortType": "desc",
                "Search": [{ "Condition": "cCusName" },
                { "condition": "cCusType", "keyword": 1 },
                { Condition: "cCusName", Keyword: this.CustomSeach }]
            }
        ).then(res => {
            this.loading = false;
            if(res.Data[0]){
                this.queryParam.CusId = res.Data[0].Id;
                this.cCusCode = res.Data[0].cCusCode;
                this.customName = res.Data[0].cCusAbbName
            }
            this.getDataList()
        }).catch(err => {
            this.$message.error(err)
        })

    },

    data() {
        return {
            data: [],
            form: {},
            title: '',
            pagination: {
                current: 1,
                pageSize: 25,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            salesmanpagination: {
                current: 1,
                pageSize: 25,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            Custompagination: {
                current: 1,
                pageSize: 25,
                showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
                pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
                showSizeChanger: true
            },
            selectedRowKeysRadio: [],
            selectedRowKeysSalesman: [],
            filters: {},
            salesmanloading: false,
            sorter: { field: 'dDate', order: 'desc' },
            loading: false,
            Customloading: false,
            columns,
            columnsSalesman,
            columnsCus,
            cCusCode: '',
            county: [],
            listChildren: [],
            list: [],
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
            queryParam: {
                "CusId": "",
            },
            rules: {
                cCusTaxnumber: [{ pattern: /^[0-9a-zA-Z]{18}$/, message: '请输入18位税号', trigger: 'blur' },],
                cCusCode: [{ required: true, message: '未输入', trigger: 'blur' }],
                cCusName: [{ required: true, message: '未输入', trigger: 'blur' }],
            },
            selectedRowKeys: [],
            visible: false,
            customName: '',
            businessVisible: false,
            salesmanData: [],//业务员数据
            salesmanQueryParam: { Condition: 'cCusName' },
            CustomData: [],//客户数据
            CustomSeach: '',
            visibleUpload: false,
        }
    },
    computed: {
        rowSelectionBusiness() {
            return {
                selectedRowKeys: this.selectedRowKeysRadio,
                type: 'radio',
                onChange: this.onSelectChangeRadio,
            }
        },
        rowSelectionSalesman() {
            return {
                selectedRowKeys: this.selectedRowKeysSalesman,
                onChange: this.onSelectChangeSalesman,
                // onSelect: this.onSelect,
                // onSelectAll: this.onSelectAll,
                // getCheckboxProps: record => ({
                //     props: {
                //         disabled: record.Openedquantity >= record.quantity, // Column configuration not to be checked
                //         name: record.name,
                //     },
                // })
            }
        }
    },
    methods: {
        repossess() {
            this.salesmanQueryParam = { Condition: 'cCusName' }
        },
        handleTableChange(pagination, filters, sorter) {
            this.pagination = { ...pagination }
            this.filters = { ...filters }
            this.getDataList()
        },
        handleTableSalesmanChange(pagination, filters, sorter) {
            this.salesmanpagination = { ...pagination }
            this.filters = { ...filters }
            this.getDataList()
        },
        handleTableCustomChange(pagination, filters, sorter) {
            this.Custompagination = { ...pagination }
            this.filters = { ...filters }
            this.getCustomData()
        },
        // 导入文件类型
        handleChange(info) {
            if (info.file.status !== 'uploading') {
            }
            if (info.file.status === 'done') {
                if (info.file.response.Success === false) {
                    this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
                } else {
                    this.$message.success(`${info.file.name}  文件上传成功！`)
                    this.getDataList()
                }
                this.visible = false
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} 文件上传失败！`)
            }
        },
        getDataList() {
            this.selectedRowKeys = []
            this.loading = true
            this.$http
                .post('/CustomerManagement/CustomerSalesman/GetDataList', {
                    PageIndex: this.pagination.current,
                    PageRows: this.pagination.pageSize,
                    SortField: 'id',
                    SortType: 'desc',
                    Search: {
                        "Condition": 'CusId',
                        "Keyword": this.queryParam.CusId
                    }
                })
                .then(resJson => {
                    this.loading = false
                    this.data = resJson.Data
                    if (this.data) {
                        const pagination = { ...this.pagination }
                        pagination.total = resJson.Total
                        this.pagination = pagination
                    }
                }).catch(err => {
                    this.$message.error(err)
                })
        },
        downloadTemplate() {

        },
        //导入
        handleImport() {
            this.visibleUpload = true;
        },
        handleCancel() {
            this.close();
        },
        //获取商家数据
        getCustomData() {
            this.Customloading = true;
            this.$http.post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition',
                {
                    "PageIndex": this.Custompagination.current, "PageRows": this.Custompagination.pageSize,
                    "SortField": "Id", "SortType": "desc",
                    "Search": [{ "Condition": "cCusName" },
                    { "condition": "cCusType", "keyword": 1 },
                    { Condition: "cCusName", Keyword: this.CustomSeach }]
                }
            ).then(res => {
                this.Customloading = false;
                this.CustomData = res.Data;
                if (this.CustomData) {
                    const pagination = { ...this.Custompagination }
                    pagination.total = res.Total
                    this.Custompagination = pagination
                }
            }).catch(err => {
                this.$message.error(err)
            })
        },
        //获取业务员数据
        getSalesmanData() {
            this.salesmanloading = true;
            this.$http.post('/CustomerManagement/CustomerSalesman/GetDataList',
                {
                    "PageIndex": this.salesmanpagination.current, "PageRows": this.salesmanpagination.pageSize,
                    "SortField": "Id", "SortType": "desc",
                    Search: this.salesmanQueryParam,
                }
            ).then(res => {
                this.salesmanloading = false;
                this.salesmanData = res.Data;
                if (this.salesmanData) {
                    const pagination = { ...this.salesmanpagination }
                    pagination.total = res.Total
                    this.salesmanpagination = pagination
                }
            }).catch(err => {
                this.$message.error(err)
            })
        },
        //选择客户确定
        handleCustomOK() {
            if (this.selectedRowKeysRadio.length <= 0) {
                this.$message.error('请选择一个客户!')
            }
            this.queryParam.CusId = this.selectedRowKeysRadio[0].Id
            this.cCusCode = this.selectedRowKeysRadio[0].cCusCode
            this.customName = this.selectedRowKeysRadio[0].cCusAbbName
            this.businessVisible = false;
            this.getDataList();
        },
        close() {
            this.visible = false;
            // this.salesmanQueryParam.Condition = "cCusName"
            // this.salesmanQueryParam.Keyword = "";
            this.form = {};
        },
        //新增购买方添加
        handleOk() {
            this.$refs['form'].validate((valid) => {
                if (!valid) {
                    return
                }
                // let arr = [];
                // this.selectedRowKeysSalesman.forEach(item => {
                //     arr.push({ SaleId: item })
                // })
                this.$http.post('/CustomerManagement/CustomerSalesman/SaveData', {
                    ...this.form,
                    "CusId": this.queryParam.CusId
                }).then(res => {
                    if (res.Success) {
                        this.$message.success('保存成功');
                        this.visible = false;
                        this.getDataList();
                    } else {
                        this.$message.error(res.Msg)
                    }
                }).catch(err => {
                    this.$message.error(err)
                })
            })
        },
        onSelectChangeRadio(selectedRowKeys) {
            this.selectedRowKeysRadio = selectedRowKeys
        },
        onSelectChangeSalesman(selectedRowKeys) {
            this.selectedRowKeysSalesman = selectedRowKeys
        },
        hasSelected() {
            return this.selectedRowKeys.length > 0
        },
        handleAdd() {
            this.$refs.editForm.openForm(null, '新建销售出库单主表信息')
        },
        // handleEdit(id) {
        //     this.$refs.editForm.openForm(id, '出库单详情')
        // },
        handleDelete(ids) {
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.post('/CustomerManagement/CustomerSalesmanAction/DeleteData', [ids]).then(res => {
                    if (res.Success) {
                        this.$message.success('删除成功!')
                    } else {
                        this.$message.error(res.Msg)
                    }
                    this.getDataList();
                }).catch(err => {
                    this.$message.error(err)
                })
            }).catch(err => {
                this.$message.info('取消删除')
            })
        },
        //选择商家
        handleOpenChoose() {
            this.businessVisible = true;
            this.getCustomData();
        },
        //关联业务员    
        association() {
            this.selectedRowKeysSalesman = [];
            this.getSalesmanData();
            this.visible = true;
            this.form = {};
            this.title = '新增';
        },
        handleEdit(id) {
            this.visible = true;
            this.title = '编辑';
            this.$http.post('/CustomerManagement/CustomerSalesman/GetTheData', { id }).then(res => {
                this.form = res.Data
                this.getlist()
                this.city(this.form.cProvince)
                this.village(this.form.cCity)
            })

        },
        // 获取省份信息
        getlist(e) {
            this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=0', {}).then(resJson => {
                this.loading = false
                this.list = resJson.Data
            })
        },
        // 市级change
        city(e) {
            this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
                this.loading = false
                this.listChildren = resJson.Data
                delete this.queryParam[2].keyword
                delete this.queryParam[3].keyword
            })
        },
        // 县change
        village(e) {
            this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
                this.loading = false
                this.county = resJson.Data
            })
        },
        timeFormat(val) {
            // 时间格式化函数
            return moment(val).format('YYYY-MM-DD HH:mm')
        }
    }
}
</script>